<?php
/**
 *  💡 免责声明：本软件不得用于商业用途，仅做学习交流
 *  ⚠️ 权利声明：本软件由版权人提供产品技术支持
 *  📅 项目编号：NX2025-0135
 */
namespace App\Service\Group;

use App\Models\ControlList;
use App\Models\GroupOrder;
use App\Models\GroupOrderSetting;
use App\Models\OrderBatch;
use App\Service\AdvanceCard\AdvanceCardService;
use App\Service\BaseService;
use App\Service\Setting\BeanSettingService;
use App\Service\User\BeanAccountService;
use App\Service\User\WalletAccountService;
use Illuminate\Support\Facades\DB;

class BatchOrderService extends BaseService
{
    protected $batch_size;

    /**
     * @param $batch_size
     * @param mixed $userId
     */
    public function __construct($userId)
    {
        $this->batch_size = $this->getSessionSize($userId);
    }

    public function getSessionSize($user_id)
    {
        $isList = ControlList::query()->where('user_id', $user_id)->first();
        if ($isList) {
            switch ($isList->status) {
                case 0:
                    $control = $isList->control;
                    break;
                case 1:
                    $control = 1;
                    break;
                case 2:
                    $control = 999999999;
                    break;
            }
        } else {
            $control = GroupOrderSetting::query()->first()->win_interval;
        }
        return $control;
    }

    /**
     * 处理用户下单.
     *
     * @param int $userId 用户ID
     * @param int $sessionId 场次ID
     * @param float $amount 订单金额
     * @param array $quantity 订单数量
     * @param mixed $advance_card
     * @return array 处理结果
     */
    public function processOrder(int $userId, int $sessionId, float $amount, $quantity, $advance_card = null): array
    {
        $setting = BeanSettingService::make()->getSetting();
        $bean_now_price = $setting['PRICE'];  //KC通证单价
        $beanUnitPrice = bcmul(bcdiv($amount, $bean_now_price, 2), $setting['PAYMENT'], 2);
        $bean = bcmul($beanUnitPrice, $quantity, 2); //支付总价百分比的数量 unit_price burn

        if (BeanAccountService::make()->checkTheBalance($userId) < $bean) {
            $this->ExitResponse('KC通证余额不足！', 7);
        }
        if ($advance_card) {
            $_amount = 0;
        } else {
            if (WalletAccountService::make()->checkTheBalance($userId) < $amount) {
                $this->ExitResponse('钱包余额不足！', 7);
            }
            $_amount = $amount;
        }

        return DB::transaction(function () use ($userId, $sessionId, $_amount, $bean_now_price, $bean, $quantity, $advance_card, $beanUnitPrice, $amount) {
            // 获取或创建有效批次
            $batch = $this->getActiveBatch($sessionId, $userId);
            $cumulative_orders = $batch->cumulative_orders;
            $totalAmount = bcmul($amount, $quantity, 2);
            $data = [
                'order_count' => $batch->order_count + $quantity,
                'cumulative_orders' => $cumulative_orders,
                'payment_bean' => bcadd($batch->payment_bean, $bean, 2),
                'payment_balance' => bcadd($batch->payment_balance, bcmul($_amount, $quantity, 2), 2),
                'failure_count' => $batch->failure_count,
                'success_count' => $batch->success_count,
                'advance_card' => $advance_card->id ?? 0,
                'bean_unit_price' => $beanUnitPrice,
                'balance_unit_price' => $amount,
            ];

            for ($i = 0; $i < $quantity; ++$i) {
                // 检查是成功
                if ($cumulative_orders + 1 >= $this->batch_size) {
                    $this->fulfillBatch([
                        'user_id' => $userId,
                        'session_id' => $sessionId,
                        'batch_id' => $batch->id,
                        'product_id' => 1,
                        'order_no' => genOrderNumber(),
                        'amount' => $amount,
                        'gold_amount' => $beanUnitPrice,
                        'number' => 1,
                        'is_winner' => 1,
                        'is_forced' => 0,
                        'user_order_count' => $data['cumulative_orders'],
                        'bean_unit_price' => $bean_now_price,
                        'bean_burn' => $beanUnitPrice,
                        'make_an_appointment' => 1,
                        'is_card' => $_amount == 0 ? 1 : 0,
                        'card_id' => $advance_card->id ?? 0,
                    ]);
                    ++$data['success_count'];
                    $cumulative_orders = 0;
                } else {
                    ++$data['failure_count'];
                    ++$cumulative_orders;
                }
            }
            $data['cumulative_orders'] = $cumulative_orders;
            $batch->update($data);

            AdvanceCardService::make()->voucherConsumptionAmount($userId, $totalAmount, sprintf('参加%s次拼团 消耗代金券%s', $quantity, $totalAmount));
            if ($_amount > 0) {
                WalletAccountService::make()->consumption($userId, $_amount, '拼单钱包消费:' . $_amount, 2);
            }
            BeanAccountService::make()->consumption($userId, $bean, sprintf('拼单KC通证消费:%s', $bean));
            return $data;
        });
    }

    /**
     * 获取用户的有效批次
     * @param mixed $userId
     */
    protected function getActiveBatch(int $sessionId, $userId)
    {
        $model = OrderBatch::query()
            ->lockForUpdate()
            ->firstOrCreate(
                [
                    'user_id' => $userId,
                    'session_id' => $sessionId,
                ],
                [
                    'cumulative_orders' => 0,
                    'success_count' => 0,
                    'failure_count' => 0,
                    'payment_bean' => 0,
                    'payment_balance' => 0,
                    'reward_contribution' => 0,
                    'point_burning_reward' => 0,
                    'bean_burning_reward' => 0,
                    'advance_card' => 0,
                    'status' => 0,
                    'bean_unit_price' => 0,
                    'balance_unit_price' => 0,
                ]
            );
        if ($model->wasRecentlyCreated) {
            //cumulative_orders 5
            $lastOrderBatch = OrderBatch::query()
                ->where('user_id', $userId)
                ->where('id', '<>', $model->id)
                ->latest('id')
                ->first();
            $lastOrderCount = $lastOrderBatch->cumulative_orders ?? 0;
            if ($lastOrderCount > 0 && $lastOrderCount < $this->batch_size) {
                $nowOrderCount = $lastOrderBatch->cumulative_orders;
            } else {
                $nowOrderCount = 0;
            }
            $model->update([
                'cumulative_orders' => $nowOrderCount,
            ]);
        }
        return $model;
    }

    /**
     * 处理满20单的发货逻辑.
     */
    protected function fulfillBatch(array $data)
    {
        // 创建成功订单记录
        $order = GroupOrder::query()->create($data);
    }
}
